package com.xmlt.ui.builder;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import com.xmlt.core.template.TemplateManager;

public class BuilderPlugin extends AbstractUIPlugin {
	// The plug-in ID
	public static final String PLUGIN_ID = "com.xmlt.ui.editors"; //$NON-NLS-1$

	public static final String RESOLVER_FACTORY_EXT_ID = "com.xmlt.ui.builder.ResolverFactory";

	// The shared instance
	private static BuilderPlugin plugin;
	
	private IResolverFactory resolverFactory;

	/**
	 * The constructor
	 */
	public BuilderPlugin() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
		IConfigurationElement[] resolverConfigs = Platform
				.getExtensionRegistry().getConfigurationElementsFor(
						RESOLVER_FACTORY_EXT_ID);
		if (resolverConfigs.length > 0) {
			resolverFactory = (IResolverFactory) resolverConfigs[0].createExecutableExtension("class");
		} else {
			resolverFactory = new DefaultResolverFactory();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static BuilderPlugin getDefault() {
		return plugin;
	}
	
	public static TemplateManager getTemplateManager(IProject project) {
		XMLTNature xmltNature = null;
		try {
			xmltNature = (XMLTNature) project.getNature(XMLTNature.NATURE_ID);
		} catch (CoreException e) {
			// e.printStackTrace();
		}
		if (xmltNature == null)
			throw new RuntimeException("Project " + project.getName()
					+ " does not have XMLT nature.");

		return xmltNature.getTemplateManager();
	}

	public static void waitForBuilderInit(IProject project) {
		XMLTNature xmltNature = null;
		try {
			xmltNature = (XMLTNature) project.getNature(XMLTNature.NATURE_ID);
		} catch (CoreException e) {
			// e.printStackTrace();
		}
		if (xmltNature != null)
			xmltNature.waitForInit();
	}
	
	public IResolverFactory getResolverFactory() {
		return resolverFactory;
	}
}
